﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZkSurvey.BLL.SurveyMgr;
using ZkSurvey.Common.SurveyMgr;
using ZkSurvey.Web.Helper;

namespace ZkSurvey.Web.VP.SurveyResult
{
    public partial class Audit : System.Web.UI.UserControl
    {
        QuestionBl questionBl = new QuestionBl();
        SurveyBl surveyBl = new SurveyBl();
        ExternalUserBl extUserBl = new ExternalUserBl();
        AnswerBl answerBl = new AnswerBl();
        ParticipationBl particBl = new ParticipationBl();

        protected void Page_Load(object sender, EventArgs e)
        {
            //根据是否传进来参数ExternalUserId 来判断是查看问卷还是查看问卷结果
            if (!IsPostBack)
            {
                LoadInfo();

                BindQuestions();
            }
            MessageHelper.Prepare(this.Page);
        }

        private void LoadInfo()
        {
            int? particId = UrlHelper.GetQueryStringID();
            if (!particId.HasValue)
                ErrorHelper.RaiseNoValueError();
            Participation partic = extUserBl.GetParticipation(particId.Value);
            ViewState["ParticId"] = particId.Value;

            int svId = partic.SurveyId;
            ViewState["SurveyId"] = svId;


            ltrJoinTime.Text = partic.JoinTime.ToString("yyyy-MM-dd HH:mm");
            ltrStatus.Text = partic.ValidStatus;
            List<Answer> answers = answerBl.GetAnswerList(particId.Value);
            int validCount = answers.Count(a => !string.IsNullOrEmpty(a.Result));
            int totalCount = answers.Count;
            ltrCompleteExtent.Text = string.Format("{0}/{1}", validCount, totalCount);

            if (partic.IsValid.HasValue)
            {
                if (partic.IsValid.Value)
                {
                    BtnValid.Visible = false;
                    BtnInValid.Visible = true;
                }
                else
                {
                    BtnValid.Visible = true;
                    BtnInValid.Visible = false;
                }
            }
        }

        private void BindQuestions()
        {
            int svId = Convert.ToInt32(ViewState["SurveyId"]);

            List<Question> questions = questionBl.GetQuestionList(svId);
            rptQuestions.DataSource = questions;
            rptQuestions.DataBind();

            Survey survey = surveyBl.GetSurvey(svId);
            ltrQuesCount.Text = questions.Count.ToString();
            ltrSvTitle.Text = survey.Title;
            ltrSvDesciption.Text = survey.Description;
        }

        protected void rptQuestions_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Question question = e.Item.DataItem as Question;
                Answer answer = answerBl.GetAnswer(Convert.ToInt32(ViewState["ParticId"]), question.Id);

                Literal ltrQueTitle = e.Item.FindControl("ltrQuesTitleFormat") as Literal;
                ltrQueTitle.Text = string.Format("{0}.{1}", question.Sort, question.Title);

                RadioButtonList rblOptions = e.Item.FindControl("rblOptions") as RadioButtonList;
                CheckBoxList cblOptions = e.Item.FindControl("cblOptions") as CheckBoxList;
                TextBox tbxResult = e.Item.FindControl("tbxResult") as TextBox;
                TextBox tbxUserInput = e.Item.FindControl("tbxUserInput") as TextBox;


                if (question.Type == QuestionType.Single)
                {
                    tbxResult.Visible = false;
                    cblOptions.Visible = false;
                    if (!question.AllowInput)
                        tbxUserInput.Visible = false;
                    else
                        tbxUserInput.Text = answer.UserInput;

                    BindOptions(rblOptions, question);

                    rblOptions.SelectedValue = answer.Result;
                }
                else if (question.Type == QuestionType.Multiple)
                {
                    tbxResult.Visible = false;
                    rblOptions.Visible = false;
                    if (!question.AllowInput)
                        tbxUserInput.Visible = false;
                    else
                        tbxUserInput.Text = answer.UserInput;

                    BindOptions(cblOptions, question);

                    //cblOptions.SelectedValue
                    if (!string.IsNullOrEmpty(answer.Result))
                    {
                        string[] ids = answer.Result.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        foreach (ListItem cblItem in cblOptions.Items)
                        {
                            if (ids.Contains(cblItem.Value))
                            {
                                cblItem.Selected = true;
                            }
                        }
                    }

                }
                else if (question.Type == QuestionType.Input)
                {
                    cblOptions.Visible = false;
                    rblOptions.Visible = false;
                    tbxUserInput.Visible = false;
                    tbxResult.Text = answer.Result;
                }
            }
        }
        
        private void BindOptions(ListControl lst, Question question)
        {
            lst.DataSource = question.Options;
            lst.DataTextField = "FormatedName";
            lst.DataValueField = "Id";
            lst.DataBind();
        }

        protected void BtnValid_Click(object sender, EventArgs e)
        {
            int paticId = Convert.ToInt32(ViewState["ParticId"]);
            Participation partic = particBl.GetParticipation(paticId);
            partic.IsValid = true;
            particBl.UpdateParticipation(partic);
            LoadInfo();

            MessageHelper.RegShowJSAjax(this.BtnValid, "操作成功：此份问卷设置为有效", this.Page);
        }

        protected void BtnInValid_Click(object sender, EventArgs e)
        {
            int paticId = Convert.ToInt32(ViewState["ParticId"]);
            Participation partic = particBl.GetParticipation(paticId);
            partic.IsValid = false;
            particBl.UpdateParticipation(partic);
            LoadInfo();

            MessageHelper.RegShowJSAjax(this.BtnInValid, "操作成功：此份问卷设置为无效", this.Page);

        }
    }
}